package org.punkgrok.flightrecorder;

import org.punkgrok.flightrecorder.mock.MockHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Proxy;
import java.util.Calendar;
import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * User: Roman Florian Zabicki III
 * Date: May 29, 2009
 * Time: 8:02:44 PM
 */
public class ProxyBasedTestCodeBuilder implements TestCodeBuilder {
	public String buildTestMethod(HttpServletRequest request) {
		List<MethodInvocation> invokedMethods =
			((HttpServletRequestInvocationHandler) Proxy.getInvocationHandler(request)).getInvokedMethods();

		return getTestMethodDeclaration() + getTestMethodBody(invokedMethods) + "}\n";
	}

	protected String getTestMethodBody(List<MethodInvocation> invokedMethods) {
		return MockHttpServletRequest.buildReplayRequest(invokedMethods);
	}

	protected String getTestMethodDeclaration() {
		return
			"@Test\n" +
			"public void " + getMethodName() + "() {\n";
	}

	protected String getMethodName() { //testErrorFrom_Mon_May_25_2009_at_23_48_28_CDT
		Date now = getCalendar().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("EEE_MMM_dd_yyyy_zzz'_at_'HH_mm_ss");

		return "testErrorFrom_" + sdf.format(now);
	}

	protected Calendar getCalendar() {
		return Calendar.getInstance();
	}	
	
}
